package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"time"
)

func doWrites(conn net.Conn, c chan bool) {
	in := bufio.NewReader(os.Stdin)
	for {
		s, err := in.ReadString('\n')
		if err != nil {
			conn.Close()
			log.Fatalln("Input error:", err)
		}

		_, err2 := conn.Write([]byte(s))
		if err2 != nil {
			conn.Close()
			log.Fatalln("Send error:", err2)
		}
	}
}

func doReads(conn net.Conn, c chan bool) {
	resp := make([]byte, 4096)
	for {
		r, err := conn.Read(resp)
		if r > 0 {
			fmt.Print(string(resp[:r]))
		}
		if err != nil {
			log.Fatalln("Connection closed:", err)
			break
		}
	}
}

func main() {

	if len(os.Args) > 3 || len(os.Args) < 2 {
		log.Fatalf("Usage:\ngotelnet <host> <port>\nor\ngotelnet <port>\n")
	}
	var conn net.Conn
	var err error
	if len(os.Args) == 2 {
		conn, err = net.Dial("tcp", "localhost:"+os.Args[1])
	}
	if len(os.Args) == 3 {
		conn, err = net.Dial("tcp", os.Args[1]+":"+os.Args[2])
	}
	if err != nil {
		log.Fatalln("Error connecting:", err)
	}
	fmt.Println("Connected.")
	c := make(chan bool)
	go doReads(conn, c)
	go doWrites(conn, c)
	if <-c {
		return
	}
}
